import { Button, Form, InputNumber, Spin } from "antd";
import SaveIcon from "@/assets/images/save.png?jsx";
import { useAtom, useAtomValue } from "jotai";
import { alertSettingAtom } from "@/store/alert";
import { useState } from "react";
import useFetch from "@/lib/hooks/useFetch";
import { getLimitWarning, updateLimitWarning } from "@/lib/api/alert";
import { tokenAtom } from "@/store/user";
import { useMessage } from "@/providers/AntdMessageProvider";

export default function Alert() {
  const [alertSetting, setAlertSetting] = useAtom(alertSettingAtom);
  const [setting, setSetting] = useState({ ...alertSetting });

  const token = useAtomValue(tokenAtom);

  const message = useMessage();
  const { isLoading } = useFetch({
    fetchFn: () =>
      getLimitWarning(token).then((res) => {
        if (res.code !== 200) {
          throw res;
        }
        return res.data;
      }),
    immediate: true,
    onSuccess(data) {
      setSetting({
        humidityHigh: data.hWarningLimitUpper,
        humidityLow: data.hWarningLimitLower,
        pressureHigh: data.pWarningLimitUpper,
        pressureLow: data.pWarningLimitLower,
        temperatureHigh: data.tWarningLimitUpper,
        temperatureLow: data.tWarningLimitLower,
      });
    },
  });

  const { isLoading: isSaving, refetch: update } = useFetch({
    fetchFn: (data: {
      hWarningLimitLower: number;
      hWarningLimitUpper: number;
      pWarningLimitLower: number;
      pWarningLimitUpper: number;
      tWarningLimitLower: number;
      tWarningLimitUpper: number;
    }) =>
      updateLimitWarning(data, token).then((res) => {
        if (res.code !== 200) {
          throw res;
        }
      }),
    onSuccess() {
      message.success("保存成功");
    },
    onError(error) {
      let _message = "保存失败";
      if ("msg" in error) {
        _message = error.msg;
      } else if ("message" in error) {
        _message = error.message;
      }
      message.error(_message);
    },
  });

  function handleSave() {
    setAlertSetting(setting);
    update({
      hWarningLimitLower: setting.humidityLow,
      hWarningLimitUpper: setting.humidityHigh,
      pWarningLimitLower: setting.pressureLow,
      pWarningLimitUpper: setting.pressureHigh,
      tWarningLimitLower: setting.temperatureLow,
      tWarningLimitUpper: setting.temperatureHigh,
    });
  }

  return (
    <div className="h-full p-6">
      <Spin spinning={isLoading}>
        <Form>
          <div className="grid grid-cols-3 gap-x-8">
            <Form.Item
              className="col-start-1 row-start-1"
              label={<div>温度超调 (上限)</div>}
            >
              <InputNumber
                className="w-full"
                value={setting.temperatureHigh}
                onChange={(v) => {
                  setSetting({ ...setting, temperatureHigh: v || 0 });
                }}
              />
            </Form.Item>
            <Form.Item
              className="col-start-1 row-start-2"
              label={<div>温度超调 (下限)</div>}
            >
              <InputNumber
                className="w-full"
                value={setting.temperatureLow}
                onChange={(v) => {
                  setSetting({ ...setting, temperatureLow: v || 0 });
                }}
              />
            </Form.Item>
            <Form.Item
              className="col-start-2 row-start-1"
              label={<div>湿度超调 (上限)</div>}
            >
              <InputNumber
                className="w-full"
                value={setting.humidityHigh}
                onChange={(v) => {
                  setSetting({ ...setting, humidityHigh: v || 0 });
                }}
              />
            </Form.Item>
            <Form.Item
              className="col-start-2 row-start-2"
              label={<div>湿度超调 (下限)</div>}
            >
              <InputNumber
                className="w-full"
                value={setting.humidityLow}
                onChange={(v) => {
                  setSetting({ ...setting, humidityLow: v || 0 });
                }}
              />
            </Form.Item>
            <Form.Item
              className="col-start-3 row-start-1"
              label={<div>压力超调 (上限)</div>}
            >
              <InputNumber
                className="w-full"
                value={setting.pressureHigh}
                onChange={(v) => {
                  setSetting({ ...setting, pressureHigh: v || 0 });
                }}
              />
            </Form.Item>
            <Form.Item
              className="col-start-3 row-start-2"
              label={<div>压力超调 (下限)</div>}
            >
              <InputNumber
                className="w-full"
                value={setting.pressureLow}
                onChange={(v) => {
                  setSetting({ ...setting, pressureLow: v || 0 });
                }}
              />
            </Form.Item>
          </div>
        </Form>
        <div className="mt-10 text-center">
          <Button
            size="large"
            className="relative w-40"
            loading={isSaving}
            onClick={handleSave}
          >
            <SaveIcon className="absolute left-2 size-6" />
            保存
          </Button>
        </div>
      </Spin>
    </div>
  );
}
